// calendar.js
Page({
    data: {
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        weeksArr: ['日', '一', '二', '三', '四', '五', '六'],
        nowMonth: new Date().getMonth() + 1, //本月是几月
        nowDay: new Date().getDate(), //本月当天的日期
        lastMonthDays: [], //上一个月
        nowMonthDays: [], //本月
        nextMonthDays: [], //下一个月
        historyList: [],
        score: getApp().globalData.score,
        awemeId: "UUEnglishClub",
        width: 544,
        height: 144,
        padding: 32,
        fixed: false,
        isShowFollow: false,
        isShowShare: false,
        isSignIn: "",
    },
    onLoad: function () {
        let app = getApp();
        const historyList = tt.getStorageSync('historyList');
        const isShowFollow = tt.getStorageSync('isShowFollow');
        const isShowShare = tt.getStorageSync('isShowShare');
        const isSignIn = tt.getStorageSync('isSignIn');
        //const points = tt.getStorageSync('points');
        this.setData({
            historyList: historyList,
            isShowFollow: isShowFollow,
            isShowShare: isShowShare,
            isSignIn: isSignIn,
        });
        this.setData({
            score: getApp().globalData.score,
        });
        tt.showShareMenu({
            // 设置是否使用带 shareTicket 的转发，默认为 false，即不使用
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
    },
    async onShareAppMessage(option) {
        return {
            path: `/pages/index/index?from=sdf&isShare=true`, // ?后面的参数会在转发页面打开时传入onLoad方法
            templateId: "38n62h55i5ab5mae4f", // templateId为开发者后台申请的分享 ID
            title: "页面传入的分享标题",
            success() {
                console.log("分享成功");
                tt.setStorageSync('isShowShare', true);
                this.setData({
                    isShowShare: true,
                });
                let app = getApp();
                app.globalData.score += 10;
                tt.showToast({
                    title: '分享成功，获得10分',
                    icon: 'success', // 隐藏默认图标
                    duration: 1500, // 设置显示时长，根据单词长度调整
                    mask: true,
                });
                this.setData({
                    score: app.globalData.score,
                });
            },
            fail(e) {
                console.log("分享面板调起失败", e);
            },
        };
    },
    toFollow: function () {
        tt.followAwemeUser({
            awemeId: "UUEnglishClub",
            success: (res) => {
                tt.setStorageSync('isShowFollow', true);
                this.setData({
                    isShowFollow: true,
                });
                let app = getApp();
                app.globalData.score += 20;
                tt.showToast({
                    title: '关注成功，获得20分',
                    icon: 'success', // 隐藏默认图标
                    duration: 1500, // 设置显示时长，根据单词长度调整
                    mask: true,
                });
                this.setData({
                    score: app.globalData.score,
                });
            },
            fail: (res) => {
                console.log("引导关注抖音号失败，错误信息:", res.errMsg);
            },
        });
    },
    toHome: function () {
        // 在 js 文件中
        tt.redirectTo({
            url: 'index'
        });
    },
    toSignIn: function () {
        let app = getApp();
        let currentDate = new Date();
        let year = currentDate.getFullYear();
        let month = currentDate.getMonth() + 1; // 月份是从0开始计数的，所以需要加1
        let day = currentDate.getDate();
        let formattedDate = year + '-' + month + '-' + day;

        if (formattedDate !== this.data.isSignIn) {
            tt.setStorageSync('isSignIn', formattedDate);
            this.setData({
                isSignIn: formattedDate,
            });
            app.globalData.score += 1;
            tt.showToast({
                title: '签到成功，获得1分',
                icon: 'success', // 隐藏默认图标
                duration: 1500, // 设置显示时长，根据单词长度调整
                mask: true,
            });
            this.setData({
                score: app.globalData.score,
            });
        } else {
            tt.showToast({
                title: '今天已经签到过啦！',
                icon: 'success', // 隐藏默认图标
                duration: 1500, // 设置显示时长，根据单词长度调整
                mask: true,
            });
        }
    },
    readHistory: function (event) {
        tt.setStorageSync('readHistory', event.currentTarget.dataset.item);
        tt.redirectTo({
            url: 'index'
        });
    },

    getNowMonthDays(year, month) {
        let {
            nowMonth,
            nowDay
        } = this.data;
        let nowMonthDays = [];
        let days = this.getThisMonthDays(year, month); //获取当月的天数
        for (let i = 1; i <= days; i++) {
            let d = new Date(year, month - 1, i);
            let years = d.getFullYear();
            let months = d.getMonth() + 1;
            let day = d.getDate();
            let time = `${years + '/' + months + '/' + day}`; // 2023/3/3
            nowMonthDays.push({
                date: i, //几号
                week: this.data.weeksArr[new Date(year, month - 1, i).getDay()], //星期几
                time,
                color: false, //为已打卡日期样式做准备
                day, //后面会改成农历
                isNowMonthDay: month == nowMonth && i == nowDay ? "isNowMonthDay" : ""
            });
        }
        this.setData({
            nowMonthDays
        });
        console.log(nowMonthDays);
    },
    /** 获取上个月日期 */
    getLastMonthDays(year, month) {
        let nowMonthFirstDays = new Date(year, month - 1, 1).getDay();
        let lastMonthDays = [];
        if (nowMonthFirstDays) {//判断当月的第一天是不是星期天
            //上个月显示多少天
            let lastMonthNums = month - 1 < 0 ? this.getThisMonthDays(year - 1, 12) : this.getThisMonthDays(year, month - 1); //判断是否会跨年
            //上个月从几号开始显示
            for (let i = lastMonthNums - nowMonthFirstDays + 1; i <= lastMonthNums; i++) {
                let time = new Date(year, month - 2, i).toLocaleDateString(); //对应的时间
                lastMonthDays.push({
                    date: i, //几号
                    week: this.data.weeksArr[new Date(year, month - 2, i).getDay()], //星期几
                    time,
                    isNowMonthDay: ''
                });
            }
        }
        this.setData({
            lastMonthDays
        });
        console.log(lastMonthDays);
    },
    /** 获取下个月日期 */
    getNextMonthDays(year, month) {
        let {
            lastMonthDays,
            nowMonthDays
        } = this.data;
        let nextMonthDays = [];
        let nextMonthNums = lastMonthDays.length + nowMonthDays.length > 35 ? 42 - (lastMonthDays.length + nowMonthDays.length) : 35 - (lastMonthDays.length + nowMonthDays.length); //下个月显示多少天
        let nowYear = parseInt(month) + 1 > 12 ? year + 1 : year; //下一个月的年份
        let nowMonth = parseInt(month) + 1 > 12 ? 1 : parseInt(month) + 1; //下一个月的月份
        if (nextMonthNums) {//判断当前天数是否大于零
            for (let i = 1; i <= nextMonthNums; i++) {
                let time = new Date(year, month - 1, i).toLocaleDateString();
                nextMonthDays.push({
                    date: i, //几号
                    week: this.data.weeksArr[new Date(nowYear, nowMonth - 1, i).getDay()], //星期几
                    time,
                    isNowMonthDay: ''
                });
            }
        }
        this.setData({
            nextMonthDays
        });
        console.log(nextMonthDays);
    },
    /** 切换月份 */
    changeMonthFun(e) {
        let {
            year,
            month
        } = this.data;
        let type = e.currentTarget.dataset.type; //类型
        if (type == 'prev') {//上一个月
            year = month - 1 > 0 ? year : year - 1;
            month = month - 1 > 0 ? month - 1 : 12;
        } else {//next 下个月
            year = parseInt(month) + 1 > 12 ? year + 1 : year;
            month = parseInt(month) + 1 > 12 ? 1 : parseInt(month) + 1;
        }
        this.setData({
            year,
            month
        });
        this.createDays(year, month);
    },
    selectDate(e) {
        let type = e.currentTarget.dataset.type; //选择的时间类型
        let index = e.currentTarget.dataset.index; //选择的下标
        let date = e.currentTarget.dataset.item.time; //选择的下标
        let selectDate = date.replace(/\//g, "-");
        console.log("选择的时间", selectDate);
        // 自定义事件，父组件调用，回调 选择的时间selectDate
        this.triggerEvent('selectDate', selectDate);
        //将选择的时间类型的 isNowMonthDay 全改为''
        this.data[type]?.forEach((item) => {
            item.isNowMonthDay = '';
        });
        this.data[type]?.forEach((item, idx) => {
            if (index == idx) {
                item.isNowMonthDay = item.time == new Date().toLocaleDateString() ? "isNowMonthDay" : "isNotNowMonthDay"; //判断当前选中的日期是否是当前时间
            } else {
                item.isNowMonthDay = '';
            }
        });
        this.setData({
            [type]: this.data[type]
        });
    },
    onShareAppMessage: function () {
        return {
            title: '好友推荐，立享特权！尽情畅听！',
            imageUrl: "logo.jpg",
            path: ''
        };
    },
    // 点击分享按钮时执行
    onShareAppMessage: function () {
        // 返回自定义的分享内容
        return {
            title: '好友推荐，立享特权！尽情畅听',
            path: '', // 分享页面的路径
            imageUrl: 'logo.jpg' // 分享图片的路径
        };
    }
});